<?
/**
 * class CVideos
 * 
 */
class CVideos_vidwiz extends Controller_vidwiz{
  /**
   * 
   * Effettua l'upload del video, la scrittura nel database, lo spostamento del file
   * e l'aggiunta alla lista per la conversione
   * @param bool $instantConversion Se true avvia la conversione immediata del video caricato
   * @return string $newPath il path del video uploadato
   * @access public
   */
  public function uploadVideo($instantConversion = false,$installation = false,$contests = false){
      $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        if($_FILES['video'] == null) return;
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        $EVideos = USingleton_vidwiz::getInstances("EVideos_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        global $config;
        $username = $MVideos->getUsername();
        define("UPLOAD_BASE_DIR", $config['basedir_videos'].$username);
        define("UPLOAD_DIR", UPLOAD_BASE_DIR."/videos/");
        $error = array();
        if($installation == false){
            $error[] = $check->check_description($VVideos->getRequest("description"));
            $error[] = $check->check_title($VVideos->getRequest("title"));
            $error[] = $check->check_metatags($VVideos->getRequest("metatags"));
            $error[] = $check->check_allowedMIME('video',$MVideos->getAllowedMIMEs());
            if($contests == false)
                $error[] = $check->check_category($VVideos->getRequest("category"));}
        
        if(in_array(false, $error))
            die(__("C'è stato un errore nel trasferimento dei dati",'vidwiz-plugin'));
        if(!is_dir(UPLOAD_BASE_DIR)){
                $MVideos->createDir(UPLOAD_BASE_DIR);}
        if(!is_dir(UPLOAD_DIR) && !is_dir(UPLOAD_DIR."toConvert/")){
                $MVideos->createDir(UPLOAD_DIR);
                $MVideos->createDir(UPLOAD_DIR."toConvert/");
                
                }
                
        $name = $MVideos->moveFile(UPLOAD_DIR."toConvert/",'video');
        //$MVideos->createDir(UPLOAD_DIR.preg_replace($config['patterns']['extension'], "", $name)."/");
        $position = "videos/".$username."/videos/toConvert/".$name;
        $breaking = $VVideos->getRequest('vidwiz-breaking');
        if($breaking == "breaking")
            $breaking = "1";
        else $breaking = "0";
        $VideoData = $EVideos->generateObject(array(
            "description" => $VVideos->getRequest("description"),
            "title" => $VVideos->getRequest("title"),
            "metatags" => $VVideos->getRequest("metatags"),
            "publisher_username" => $username,
            "file_position" => $position,
            "category" => $VVideos->getRequest("category"),
            "converted" => "FALSE",
            "thumb" => "",
            "breaking" => $breaking
        ));
        
        $insert = $MVideos->insertQuery($VideoData);
        $MVideos->executeQuery($insert);
        if($instantConversion == true || $instantConversion == 1 || $instantConversion=="1"){
            $this->convertVideos(true);
            }
        return $position;
        
    }

    /**
     * Converte i video che ancora nn sono stati convertiti
     * @global array $config 
     * @return string $output la posizione del file convertito
     */
    public function convertVideos($breaking = false){
        global $config;     $order = "ASC";
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $where = array(array("converted","=","FALSE"));
        //Se è stata inserita una breaking news, si converte prima quella, quindi
        //nell'array $where si inserisce anche la condizione di breaking news
        if($breaking == true){
            $where[] = array("breaking",'=','1');
        }
        $query = $model->searchQuery($config['tables']['videos'], $where, array("file_position","id"));
        $rows = $model->getRows($query);
        $nRows = count($rows);  
        //Array che conterrà i path nuovi dei file convertiti 
        //(quelli che vanno nel db)
        $paths = array();
        for($i=0;$i<$config['maxContConversions'] && $i<$nRows;$i++){
            $value=$rows[$i];
            $oldPath = $value[0];
            $value[0] = $config['basedir'].$value[0];
            if(is_file($value[0])){ 
                $fileInfo = $model->getFileInfo($value[0]);
                $dirName = str_replace("toConvert", "", $fileInfo['dirname']);
                $oldPath = str_replace("toConvert", $fileInfo['filename'], $oldPath);
                $dirName = $dirName.$fileInfo['filename'];
                $model->createDir($dirName."/");
                //outputDB corretto
                $outputDB = preg_replace($config['patterns']['extension'], ".".$config['convert_extension'], $oldPath);
                $paths[] = $outputDB;
                $output = $dirName."/".$fileInfo['filename'].".".$config["convert_extension"];
                $value[0] = $model->renameFile($value[0],"_loading_conversion");
                $cmd1 = $config['ffmpeg_path']."ffmpeg -i ".$value[0]." -acodec libfaac -vcodec libx264 -vpre fast -crf 21 ".$output."_waiting_injection.".$config["convert_extension"];
                $cmd2 = "rm $value[0] ";//&> /dev/null &'
                $cmd3 = "yamdi -i ".$output."_waiting_injection.".$config["convert_extension"]." -o ".$output;
                $cmd4 = "rm ".$output."_waiting_injection.".$config["convert_extension"];
                $out = exec("($cmd1 &&  $cmd2 &&  $cmd3 &&  $cmd4) > /dev/null 2>/dev/null &");
            }
        }
        $this->checkEndedConversions();
        if($breaking == false)
            return $output;
        else return $paths;
    }
    
    public function checkEndedConversions(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        global $config;
        $where = array(
          array("converted","=","0")  
        );
        $query = $model->searchQuery($config['tables']['videos'],$where);
        $results = $model->getRowsAssoc($query);
        foreach($results as $key => $value){
            $value["file_position"] = $config['basedir'].$value["file_position"];
            $ext = array();
            preg_match($config['patterns']['extension'] ,$value["file_position"],$ext);
            $extension = $ext[0];
            $replace = str_replace($extension, "_loading_conversion".$extension, $value['file_position']);
            $value["file_position_lc"] = $replace;
            $debug->debugLog($value['file_position_lc']);
            $debug->debugLog(is_file($value['file_position_lc']));
            if((!is_file($value["file_position"]) && (!is_file($value["file_position_lc"])))){
                $outputDB = preg_replace($config['patterns']['extension'], ".".$config['convert_extension'], $value['file_position']);
                $outputDB = str_replace("toConvert/", "",$outputDB);
                $outputDB = str_replace($config['basedir'], "", $outputDB);
                preg_match($config['patterns']['filename'],$outputDB,$ext);
                $name = str_replace("/", "", $ext[0]);
                $name = preg_replace($config['patterns']['extension'], "",$name);
                $outputDB = str_replace($name, $name."/".$name, $outputDB);
                $debug->debugLog($outputDB);
                $postid = $this->insertVideoPost($value["id"]);
                $thumb = $model->getThumbFromVideo($config['basedir'].$outputDB,$outputDB);
                $update = $model->updateQuery($config['tables']['videos'],array(
                    array("file_position",$outputDB),
                    array("converted","1"),
                    array("thumb",$thumb),
                    array("post_id",$postid)),array(array("id","=",$value["id"])
                    ));
                $debug->debugLog($update);
                $model->executeQuery($update);
            }
        }
        $this->checkBreakingNews();
    }

    
    public function checkBreakingNews(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $CPal = USingleton_vidwiz::getInstances("CPalinsesto_vidwiz");
        global $config;
        $where = array(
            array("converted","=","1"),
            array("breaking","=","1")
        );
        $query = $model->searchQuery($config['tables']['videos'],$where,array("id"));
        $results = $model->getRowsAssoc($query);
        foreach($results as $value){
            $CPal->insertBreakingNews($value);
        }
    }


    
        /**
     * Ritorna gli ultimi $nr video
     * @global array $config
     * @param string $nr
     * @return array 
     */
    public function getLastVideos($nr){
        $model = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $model = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        global $config;
        $query = $model->searchQuery($config['tables']['videos'], array(array("converted","=","1")), array("*"), "0,$nr", "id DESC");
        $results = $model->getRowsAssoc($query);
        return $results;
        
    }
    
    public function insertVideoPost($videoId){
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        global $config;
        $query = $MVideos->searchQuery($config['tables']['videos'],array(array("id","=",$videoId)));
        $results = $MVideos->getRowsAssoc($query);
        $results = $results[0];
        $query = $MVideos->searchQuery("wp_users",array(array('user_login','=',$results['publisher_username'])));
        ;
        $username = $MVideos->getRowsAssoc($query);
        ;
        $userId = $username[0]['ID'];
        $catid = $results['category'];
        
        $shortcode = "[vidwiz-video id=\"$videoId\"]";
        $my_post = array(
             'post_title'       => $results['title'],
             'post_content'     => $shortcode,
             'post_status'      => 'publish',
             'post_author'      => $userId,
             'post_category'    => array($catid),
             'tags_input'       => $results['metatags']
          );
        return wp_insert_post( $my_post );
    }
    
    public function getVideoFrontend($videoId){
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $CContest = USingleton_vidwiz::getInstances("CContests_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $wordpress = USingleton_vidwiz::getInstances("UWordpress_vidwiz");
        global $config;
        $userId = $wordpress->getUserData();
        $userId = $userId->ID;
        $query = $MVideos->searchQuery($config['tables']['videos'],array(array("id","=",$videoId)));
        $results = $MVideos->getRowsAssoc($query);
        $results[0] = $this->absPathInArray($results[0], array('file_position','thumb'));
        $autostart = $VVideos->getRequest('autostart');
        
        if(!isset($autostart) || $autostart == "" || $autostart === null)
            $autostart = "0";
        else
            $autostart = "1";
        if($check->check_videoInContest($videoId,"voting")){
            $inContest = "true";
            $ratingStart = $CContest->getRating($videoId);
            
            $ratingStart = $ratingStart[0]["average"];
            if($ratingStart == "")
                $ratingStart = "0";
            }
        if($check->check_notYetRated($videoId,$userId)){
            $notYetRated = "true";
        }
        
        return $VVideos->getVideoFrontend($results,$autostart,$inContest,$ratingStart,$notYetRated);
    }

    public function vidwiz_vid_upload_page(){
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        $categories = $this->getCategories();
        return $VVideos->getUploadPage($categories);
    }
    
        public function vidwiz_vid_upload_page_contests(){
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        return $VVideos->getUploadPage_contests();
    }
    
    public function vidwiz_breaking_news_page(){
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        $categories = $this->getCategories();
        return $VVideos->getBreakingNewsPage($categories);
    }
    
    public function vidwiz_myvideos_page(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $VVideos = USingleton_vidwiz::getInstances("VVideos_vidwiz");
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $categories = $this->getCategories();
        $myvideos = $MVideos->getVideosFromUsername($MVideos->getUsername());
        foreach ($myvideos as $key => $value)
            $myvideos[$key] = $this->absPathInArray($myvideos[$key], array('file_position','thumb'));
        $debug->debugLog($myvideos);
        return $VVideos->getMyvideosPage($categories,$myvideos);
    }
    
    

} // end of CVideos
?>